﻿#region Using Statements
using System;
using System.Collections.Generic;
using EggHarvest.GraphicsSupport;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.GamerServices;
#endregion

namespace EggHarvest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Game
    {


        #region Support for loading and drawing the JPG image
        private Texture2D mBagImage;
        private Vector2 mBagPosition;

        private Texture2D mDuckImage;
        private Vector2 mDuckPosition;

        private Texture2D mChickenImage;
        private Vector2 mChickenPosition;

        private Texture2D mGeeseImage;
        private Vector2 mGeesePosition;

        #endregion


        //Prefer window size
        private const int kWindowWidth = 900;
        private const int kWindowHeight = 600;

        static public SpriteBatch sSpriteBatch; // Drawing support
        static public ContentManager sContent; // Loading textures
        static public GraphicsDeviceManager sGraphics; // Current display size

        const int kNumObjects = 4; // number of object
        // Work with the TexturedPrimitive class
        TexturedPrimitive[] mGraphicsObjects; // An array of objects

        //int mCurrentIndex = 0;

        static public Random sRan; // For generating random numbers

        //private TexturedPrimitive mBag;
        private Egg mEgg;
        Vector2 mEggPosition = new Vector2(50,75);
        private float mEggRadius = 3f;


        //Egg
        private List<TexturedPrimitive> mEggList;
        private TimeSpan mCreationTimeStamp;
        private int mTotalEgg = 0;
        private const int kEggSecInterval = 1000;

        //Game state
        static public int score = 0;
        public static int hShit = 0;
        private int eggMissed = 0;
        private const int eggTouchScore = 1;
        public static int aStatus = 0;
        private TexturedPrimitive mFinal = null;
        public static bool sChicken = false;
        public static bool sDuck = false;
        public static bool sCheese = false;


       // private MyGame mTheGame;

        public Game1()
            : base()
        {
            
            Content.RootDirectory = "Content";
            Game1.sContent = Content;

            sGraphics = new GraphicsDeviceManager(this);

            //Set preferred window size
            sGraphics.PreferredBackBufferWidth = kWindowWidth;
            sGraphics.PreferredBackBufferHeight = kWindowHeight;

            sRan = new Random();

            mCreationTimeStamp = new TimeSpan(0);
            mEggList = new List<TexturedPrimitive>();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        /// 
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            #region Init Position
            //mBagPosition = new Vector2(10f, 400f);
            //mGeesePosition = new Vector2(100f, 10f);
            //mChickenPosition = new Vector2(350f, 10f);
            //mDuckPosition = new Vector2(620f, 10f);
            #endregion

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            sSpriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            
            #region Load Image
            //mBagImage = Content.Load<Texture2D>("Ro");
            //mGeeseImage = Content.Load<Texture2D>("ngan");
            //mDuckImage = Content.Load<Texture2D>("vit");
            //mChickenImage = Content.Load<Texture2D>("ga");
            #endregion

            // Define camera window bounds
            Camera.SetCameraWindow(new Vector2(10f, 20f), 100f);

            // Create the primitives.
            mGraphicsObjects = new TexturedPrimitive[kNumObjects];
            mGraphicsObjects[0] = new TexturedPrimitive("Ro", // Image file name
                    new Vector2(30f, 25f), // Position to draw
                    new Vector2(10f, 10f)); // Size to draw
            if(aStatus==3)
                mGraphicsObjects[1] = new TexturedPrimitive("ngan", new Vector2(25f, 74f), new Vector2(10f, 10f));
            if (aStatus == 2)
                mGraphicsObjects[2] = new TexturedPrimitive("vit", new Vector2(55f, 74f), new Vector2(10f, 10f));
            if (aStatus == 1)
                mGraphicsObjects[3] = new TexturedPrimitive("ga", new Vector2(85f, 74f), new Vector2(10f, 10f));

            //Create the primitives
   
            mEgg = new Egg(mEggPosition,mEggRadius*2f);
           
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }




        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // TODO: Add your update logic here

            #region Keyboard
            //Keyboard create chicken, duck, cheese
            if (Keyboard.GetState().IsKeyDown(Keys.G))
            {
                aStatus = 1;
                sChicken = true;
                mGraphicsObjects[3] = new TexturedPrimitive("ga", new Vector2(85f, 74f), new Vector2(10f, 10f));
            }
            if (Keyboard.GetState().IsKeyDown(Keys.V))
            {
                
                aStatus = 2;
                sDuck = true;
                mGraphicsObjects[2] = new TexturedPrimitive("vit", new Vector2(55f, 74f), new Vector2(10f, 10f));
            }
            if (Keyboard.GetState().IsKeyDown(Keys.N))
            {
                aStatus = 3;
                sCheese = true;
                mGraphicsObjects[1] = new TexturedPrimitive("ngan", new Vector2(25f, 74f), new Vector2(10f, 10f));
            }

          


           # region Update the image positions with Arrow keys

            //mBagPosition += InputWrapper.ThumbSticks.Right;

            //if (Keyboard.GetState().IsKeyDown(Keys.Left))
            //{
            //    // mBagPosition.X--;
            //    mBagPosition.X -= 4;
            //}

            //if (Keyboard.GetState().IsKeyDown(Keys.Right))
            //{
            //    //mBagPosition.X++;
            //    mBagPosition.X += 4;
            //}

            /* if (Keyboard.GetState().IsKeyDown(Keys.Up))
             {
                 //mBagPosition.Y--;
                 mBagPosition.Y -= 4;
             }

             if (Keyboard.GetState().IsKeyDown(Keys.Down))
             {
                 //mBagPosition.Y++;
                 mBagPosition.Y += 4;
             }*/
           #endregion

            #endregion


            #region Mouse
            // Poll mouse state
            MouseState mMouseState = Mouse.GetState();
            // If left mouse button is pressed
            if (mMouseState.LeftButton == ButtonState.Pressed)
                mBagPosition = new Vector2(mMouseState.X,mMouseState.Y);

            // If right mouse button is pressed
            if (mMouseState.RightButton == ButtonState.Pressed)
                mGeesePosition = new Vector2(mMouseState.X, mMouseState.Y);

            #endregion


            #region Toggle full screen and window size

            // "A" to toggle to full-screen mode
            if (InputWrapper.Buttons.Back == ButtonState.Pressed)
                this.Exit();

            if (InputWrapper.Buttons.A == ButtonState.Pressed)
            {
                if (!sGraphics.IsFullScreen)
                {
                    sGraphics.IsFullScreen = true;
                    sGraphics.ApplyChanges();
                }
            }

            if (InputWrapper.Buttons.B == ButtonState.Pressed)
            {
                if (sGraphics.IsFullScreen)
                {
                    sGraphics.IsFullScreen = false;
                    sGraphics.ApplyChanges();
                }
            }
            #endregion

            #region Select object and control selected object

            // Button X to select the next object to work with
            //if (InputWrapper.Buttons.X == ButtonState.Pressed)
            //    mCurrentIndex = (mCurrentIndex + 1) % kNumObjects;

            // Update currently working object with thumb sticks.
            //mGraphicsObjects[mCurrentIndex].Update(
            //                                    InputWrapper.ThumbSticks.Left,
            //                                    InputWrapper.ThumbSticks.Right);

            mGraphicsObjects[0].UpdatePosition(InputWrapper.ThumbSticks.Right);
            mGraphicsObjects[0].UpdatePosition(InputWrapper.ComInput.Right);
            #endregion

            //mBag.Update(InputWrapper.ThumbSticks.Left, Vector2.Zero); 
            
           
            //mEgg.Update();
            //mEgg.Update(Vector2.Zero, InputWrapper.ThumbSticks.Right);

            //if(InputWrapper.Buttons.A == ButtonState.Pressed)
            //    mEgg = new Egg(mEggPosition, mEggRadius*2f);

            //mTheGame.UpdateGame(gameTime);
            //if (InputWrapper.Buttons.X == ButtonState.Pressed)
            //    mTheGame = new MyGame();

            mEgg.Fall();
            if (mGraphicsObjects[0].PrimitivesTouches(mEgg))
            {
                mEgg.Size = new Vector2(20,20);
            }

            #region step a
            if (null != mFinal)
                return;
            #endregion

            #region handle collision

            for (int b = mEggList.Count - 1; b >= 0; b--)
            {
                if (mGraphicsObjects[0].PrimitivesTouches(mEggList[b]) && mEggList[b] is Egg)
                {
                    mEggList.RemoveAt(b);
                    score++;
                }
                else
                if (mGraphicsObjects[0].PrimitivesTouches(mEggList[b]) && mEggList[b] is Shit)
                {
                    mEggList.RemoveAt(b);
                    hShit++;
                }
            }



            #endregion

            #region create new egg

            if (aStatus!=0)
            {
                TimeSpan timePassed = gameTime.TotalGameTime;
                timePassed = timePassed.Subtract(mCreationTimeStamp);

                if (timePassed.TotalMilliseconds > kEggSecInterval)
                {
                    mCreationTimeStamp = gameTime.TotalGameTime;
                    TexturedPrimitive egg = null;
                    int flag = sRan.Next(1, 4);
                    if (flag == 1 || flag == 2)
                    {
                        egg = new Egg();
                    }
                    if (flag == 3)
                    {
                        egg = new Shit();
                    }


                    mTotalEgg++;
                    mEggList.Add(egg);
                }


                for (int b = mEggList.Count - 1; b >= 0; b--)
                {
                    if (Camera.CollidedWithCameraWindow(mEggList[b]) == Camera.CameraWindowCollisionStatus.CollideBottom && mEggList[b] is Egg)
                    {
                        mEggList.RemoveAt(b);
                        eggMissed += 1;
                    }
                }

                for (int b = mEggList.Count - 1; b >= 0; b--)
                {
                    mEggList[b].Fall();
                }

                //foreach (var egg1 in mEggList)
                //{
                //    egg1.FallEgg();
                //}

            }

           
           

            #endregion

            #region Check Looser
            if(eggMissed == 3) mFinal = new TexturedPrimitive("Loser", new Vector2(75,50),new Vector2(30,20) );
            if (hShit == 3) mFinal = new TexturedPrimitive("Loser", new Vector2(75, 50), new Vector2(30, 20));
            #endregion

            base.Update(gameTime);
        }




        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            sSpriteBatch.Begin(); // Initialize drawing support

            #region Drawimage
            //Draw the JPGImage
            //sSpriteBatch.Draw(mBagImage, mBagPosition, Color.White);

            //Draw the PNGImage
            //sSpriteBatch.Draw(mGeeseImage, mGeesePosition, Color.White);
            //sSpriteBatch.Draw(mDuckImage, mDuckPosition, Color.White);
            //sSpriteBatch.Draw(mChickenImage, mChickenPosition, Color.White);
            #endregion

            // Loop over and draw each primitive
            //foreach (TexturedPrimitive p in mGraphicsObjects)
            //{
            //    p.Draw();
            //}
            mGraphicsObjects[0].Draw();
            for (int i = 1; i <= 3; i++)
            {
                if (aStatus==1)
                {
                    mGraphicsObjects[3].Draw();
                    if (sDuck)
                        mGraphicsObjects[2].Draw();
                    if (sCheese)
                        mGraphicsObjects[1].Draw();
                }
                if (aStatus == 2)
                {
                    if(sChicken)
                        mGraphicsObjects[3].Draw();
                    if (sCheese)
                        mGraphicsObjects[1].Draw();
                    mGraphicsObjects[2].Draw();
                }
                if (aStatus == 3)
                {
                    mGraphicsObjects[1].Draw();
                    if (sChicken)
                        mGraphicsObjects[3].Draw();
                    if (sDuck)
                        mGraphicsObjects[2].Draw();
                }
            }

            //mBag.Draw();
            mEgg.Draw();

            if(null != mFinal) mFinal.Draw();
            // Print out text message to echo status
            //FontSupport.PrintStatus("Selected object is:" + mCurrentIndex + " Location=" + mGraphicsObjects[mCurrentIndex].Position, null);

            FontSupport.PrintStatusAt(mGraphicsObjects[0].Position, "Selected", Color.Red);

           //FontSupport.PrintStatus("Egg Position: " + mEgg.Position,null);
            FontSupport.PrintStatus("Score: " + score,null);
           
            FontSupport.PrintStatusAt(mEgg.Position,"Radius" + mEgg.Radius,Color.Red);
           // FontSupport.PrintStatusAt(mBag.Position,mBag.Position.ToString(),Color.White);

            //mTheGame.DrawGame();

            foreach (var egg in mEggList)
            {
                egg.Draw();
            }

            if (null != mFinal)
            {
                mFinal.Draw();
            }

            FontSupport.PrintStatusAt(new Vector2(30f, 87f), "Level: " + score/20 + "       Egg: Generated(" + mTotalEgg + ")", null);
            FontSupport.PrintStatusAt(new Vector2(80f,87f),"Egg missing: "+eggMissed,null );
            FontSupport.PrintStatusAt(new Vector2(100f, 87f), "Shit: " + hShit, null);
            
            sSpriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
